package com.mygameframework.sprite;

import java.awt.Image;
import java.util.ArrayList;

/**
    The Animation class manages a series of images (frames) and
    the amount of time to display each frame.
*/
public class Animation_bak {

    private ArrayList frames;
    private long totalDuration;
    
    /*TODO 把Animation重构,让下面两变量归入sprite 中,
    以便可以让多个精灵实列引用同一动画
     * 
     */
    private int currFrameIndex;
    private long animTime;


    /**
        Creates a new, empty Animation.
    */
    public Animation_bak() {
        frames = new ArrayList();
        totalDuration = 0;
        start();
    }
    private String description;
    public Animation_bak(String des) {
        this();
        this.description=des;
    }
    @Override
    public String toString(){
        return description;
    }

    /**
        Adds an image to the animation with the specified
        duration (time to display the image).
    */
    public synchronized void addFrame(Image image,
        long duration)
    {
        totalDuration += duration;
        frames.add(new AnimFrame(image, totalDuration));
    }


    /**
        Starts this animation over from the beginning.
    */
    public synchronized void start() {
        animTime = 0;
        currFrameIndex = 0;
    }
    public synchronized void reset(){
        start();
    }

    /**
        Updates this animation's current image (frame), if
        neccesary.
    */
    public synchronized void update(long elapsedTime) {
        if (frames.size() > 1) {
            animTime += elapsedTime;

            if (animTime >= totalDuration) {
                animTime = animTime % totalDuration;
                currFrameIndex = 0;
            }

            while (animTime > getFrame(currFrameIndex).endTime) {
                currFrameIndex++;
            }
        }
    }


    /**
        Gets this Animation's current image. Returns null if this
        animation has no images.
    */
    public synchronized Image getImage() {
        if (frames.isEmpty()) {
            return null;
        }
        else {
            return getFrame(currFrameIndex).image;
        }
    }


    private AnimFrame getFrame(int i) {
        return (AnimFrame)frames.get(i);
    }


    private class AnimFrame {

        Image image;
        long endTime;

        public AnimFrame(Image image, long endTime) {
            this.image = image;
            this.endTime = endTime;
        }
    }
}
